package com.bort.system.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

public class SingleInstance {
    private static File lockFile = new File(System.getProperty("user.home") + "/.Billiards.lock");
    private static FileChannel fileChannel;
    private static FileLock fileLock;

    public static boolean createLock() {
        try {
            fileChannel = new FileOutputStream(lockFile).getChannel();
            fileLock = fileChannel.tryLock();
            if (fileLock == null) {
                // 锁被占用，程序已经在运行
                return false;
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void releaseLock() {
        try {
            if (fileLock != null) {
                fileLock.release();
            }
            if (fileChannel != null) {
                fileChannel.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}